package cn.darkfire.web.Utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.security.SecureRandom;
import java.util.Random;

public class ImageUtils {
    private BufferedImage image = null; //创建图片字节
    private static final ImageUtils instance = new ImageUtils();
    private String code = "";

     public BufferedImage initImage(){
        this.code = "";
        image = new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics(); //获取图片画板
        g.setColor(Color.WHITE); //背景颜色
        g.fillRect(0,0,100,30); //填充矩形
        g.setColor(Color.black);
        g.setFont(new Font("Times New Roman",Font.BOLD,18));
        char[] codes = "23456789zxcvbnmasdfghjklqwertyuop".toCharArray();
        Random rand = new SecureRandom(); //相比Random更加的安全,不会产生重复的伪随机数
        //开始生成验证码
        for(int i = 0;i<4;i++){
            code += codes[rand.nextInt(codes.length-1)];
        }
        g.drawString(code,20,25);
        image = decrypt(image);
        return image;
    }

    public BufferedImage initCNImage(){
        this.code = "";
        image = new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics(); //获取图片画板
        g.setColor(Color.WHITE); //背景颜色
        g.fillRect(0,0,100,30); //填充矩形
        g.setColor(Color.black);
        g.setFont(new Font("Times New Roman",Font.BOLD,18));
        Random rand = new SecureRandom(); //相比Random更加的安全,不会产生重复的伪随机数
        //开始生成验证码
        //生成中文验证码
        // 0---> B0A1
        // 1 ---> B0A2
        //94 ----> B1A1
        for(int i = 0;i<4;i++){
           byte[] bytes = new byte[2];
           int index = rand.nextInt(3755);
           int h = index/94 + Integer.valueOf("B0",16);
           int l = index/94 + Integer.valueOf("A1",16);
           bytes[0] = Integer.valueOf(h).byteValue();
        }
        g.drawString(code,20,25);
        image = decrypt(image);
        return image;
    }

    public BufferedImage decrypt(BufferedImage image) {
        Graphics g = image.getGraphics();
        int w = image.getWidth();
        int h = image.getHeight();
        Random random = new SecureRandom();
        for(int i = 0;i<4;i++){
            //开始画线 画线起点坐标加终点坐标
            int x1 = random.nextInt(30);
            int y1 = random.nextInt(30);
            int x2 = random.nextInt(30)+70;
            int y2 = random.nextInt(30)+70;
            g.setColor(Color.black);
            g.drawLine(x1,y1,x2,y2);
        }
        return image;
    }

    public BufferedImage getImage() {
        return image;
    }

    public static ImageUtils getInstance() {
        return instance;
    }

    public String getCode() {
        return code;
    }
}
